// ==UserScript==
// @name         alist auto retry
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        *://yonghome.dynv6.net:15244/*
// @match        *://192.168.68.*:5244/*
// @match        *://192.168.68.185:5244/*
// @match        *://caiyun.139.com/*
// @match        *://yun.139.com/*
// @match        *://www.91panta.cn/*
// @match        *://momoya.msns.cn:15244/*
// @require      https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js
// @require      https://scriptcat.org/lib/637/1.3.3/ajaxHooker.js
// @grant        GM_info
// @grant        GM_download
// @grant        GM_openInTab
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';

    // Your code here...
    const alistHelper={};
    alistHelper.addAutoRetry = function() {
        if ($('#jsretry').length > 0) return
        let base = $(".hope-stack .hope-c-PJLV-ihVlqVC-css");
        if (base.length == 0) {
            console.log('添加全部重试失败')
            return;
        }
        const ele = '<button id="jsretry" class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-subtle hope-c-ivMHWx-kWSPeQ-size-md hope-c-ivMHWx-dMllzy-cv hope-c-PJLV hope-c-PJLV-iikaotv-css" type="button" role="button">全部重试</button>';
        base.append(ele);
        if (alistHelper.timerRetryTask) clearInterval(alistHelper.timerRetryTask);
        alistHelper.buttonText = $('#jsretry').text();
        $('#jsretry').click(function() {
            alistHelper.loadFailTask();
	    });
    };
    alistHelper.loadFailTask = function() {
        if (alistHelper.taskList && (alistHelper.taskListIndex<alistHelper.taskList.length)){
            return;
        }
        let callback = function(response, status) {
            let data = response
            if (data.code != 200) {
                console.log(data);
                alert('接口调用失败');
                return;
            }
            alistHelper.taskList = data.data;
            alistHelper.taskListIndex = 0;
            if (data.data) {
                alistHelper.timerRetryTask = setInterval(alistHelper.retryAllTask, 1000);
                $('#jsretry').text(alistHelper.buttonText+ `${alistHelper.taskListIndex}/${alistHelper.taskList.length}`);
            }
        }
        alistHelper.makeRequest('/api/admin/task/copy/done', 'get', {},callback)
        // GM_xmlhttpRequest({
        //     url:'/api/admin/task/copy/done',
        //     method: "get",
        //     headers: {
        //         "Authorization": localStorage.getItem('token'),
        //     },
        //     onload: callback
        // });
    };
    alistHelper.retryAllTask = function() {
        let ele = $('.hope-stack.hope-c-dhzjXW.hope-c-PJLV.hope-c-PJLV-iiOQdMT-css')
        if (ele && ele.length > 0) {
            ele = ele[0]
            ele = ele.children[1]
            if (ele.children.length > 2) {
                return
            }
        }
        for (let i=alistHelper.taskListIndex;i<alistHelper.taskList.length;++i) {
            let data = alistHelper.taskList[i];
            if (data.state != 'errored') {
                continue;
            }
            alistHelper.retryTask(data.id);
            alistHelper.taskListIndex = (i+1);
            break;
        }
        $('#jsretry').text(alistHelper.buttonText+ `${alistHelper.taskListIndex}/${alistHelper.taskList.length}`);
        if (alistHelper.taskList.length <= alistHelper.taskListIndex) {
            clearInterval(alistHelper.timerRetryTask);
            alert("全部重试完成");
        }
    };
    alistHelper.retryTask = function(id) {
        let callback = function(response) {
            let status = response.code;
            let data = response
            if(!((status==200||status=='200')&&data.code == 200)){
                console.log(id, 'retry failed');
            }
        }
        alistHelper.makeRequest('/api/admin/task/copy/retry?tid='+id, 'post', {},callback)
        // GM_xmlhttpRequest({
        //     url:'/api/admin/task/copy/retry?tid='+id,
        //     method: "post",
        //     headers: {
        //         "Authorization": localStorage.getItem('token'),
        //     },
        //     onload: callback
        // });
    };
    // -------------------------------------------------------------------------------------------------------------
    alistHelper.addCompareBtn = function() {
        let base = $("nav");
        if (base.length == 0 || $('#jsCmpSrc').length > 0 || $('#jsCmpDst').length > 0) {
            let txt = $('#jsCmpSrc').text() || $('#jsCmpDst').text()
            txt = txt.split('(')[0]
            let len = $('.list.hope-c-PJLV-ihXHbZX-css').children().length-1
            txt = `${txt}(${len})`
            $('#jsCmpSrc').text(txt)
            $('#jsCmpDst').text(txt)
            return;
        }
        const btnSrc = '<button class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-solid hope-c-ivMHWx-dwWzpk-size-sm hope-c-ivMHWx-IjcEH-size-md hope-c-ivMHWx-EevEv-cv hope-c-PJLV hope-c-PJLV-ihbZbLe-css"'+
              ' type="button" role="button" id="jsCmpSrc">设置比较源</button>'
        const btnDst = '<button class="hope-button hope-c-ivMHWx hope-c-ivMHWx-kcPQpq-variant-solid hope-c-ivMHWx-dwWzpk-size-sm hope-c-ivMHWx-IjcEH-size-md hope-c-ivMHWx-EevEv-cv hope-c-PJLV hope-c-PJLV-ihbZbLe-css"'+
              'type="button" role="button" id="jsCmpDst">开始比较</button>'
        console.log('test', alistHelper.compareSrc);
        if (alistHelper.compareSrc === undefined) {
            base.children(1).append(btnSrc);
        } else {
            base.children(1).append(btnDst);
        }
        //clearInterval(alistHelper.timer);
        $('#jsCmpSrc').click(function() {
            alistHelper.compareSrc = decodeURI(window.location.pathname);
            let pathDst=prompt("请输入目标目录：")
            if (pathDst) {
                alistHelper.doCompare(alistHelper.compareSrc, pathDst);
            } else {
                $('#jsCmpSrc').remove();
                console.log(alistHelper.compareSrc)
                base.children(1).append(btnDst);
                $('#jsCmpDst').click(function() {
                    $('#jsCmpDst').remove();
                    alistHelper.addCompareBtn();
                    alistHelper.doCompare(alistHelper.compareSrc, decodeURI(window.location.pathname));
                });
            }
	    });
    };
    alistHelper.doCompare = function(src, dst) {
        let data = {'src':src, 'dst':dst, fileList:[]};
        alistHelper.listAll(src, data);
        alistHelper.listAll(dst, data);
    };
    alistHelper.compareFiles = function(files) {
        if (!(files[files.src] && files[files.dst])){
            return
        }
        let src = files['src']
        let dst = files['dst']
        let fileList = files.fileList
        let objs = {}
        if (files[dst].content) {
            for (let obj of files[dst].content) {
                objs[obj.name] = obj
            }
        }
        let sameFiles = []
        for (let obj of files[src].content) {
            if (objs[obj.name] == undefined || objs[obj.name].size != obj.size) {
                if (obj.is_dir) {
                    alistHelper.mkdir(dst + '/' + obj.name)
                } else {
                    obj.pathDst = dst
                    obj.pathSrc = src
                    if (fileList.length == 0) {
                        obj.totalSize = obj.size
                    } else {
                        fileList[0].totalSize = fileList[0].totalSize + obj.size
                    }
                    fileList.push(obj)
                    //if (fileList.length >= count || (fileList.length > 0 && fileList[0].totalSize > 50*1024*1024*1024)) {
                    //    return
                    //}
                }
            } else {
                if (!obj.is_dir) {
                    sameFiles.push(obj.name)
                }
            }
        }
        if (sameFiles.length > 0) {
            let ok = confirm('删除原文件吗？'+src)
            if (ok) {
                let delData = {"dir": src, "names":sameFiles}
                alistHelper.makeRequest('/api/fs/remove', 'post', delData, function (rsp,status) {
                    console.log('remove', rsp)
                });
            }
        }
        for (let obj of files[src].content) {
            if (obj.is_dir) {
                alistHelper.doCompare(src+'/'+obj.name, dst+'/'+obj.name)
            }
        }
        alistHelper.copyTask(src, dst, fileList)
    };
    alistHelper.listAll = function(path, files) {
        let data = {
            page: 1,
            password:"",
            path:path,
            per_page:0,
            refresh:false
        };
        alistHelper.makeRequest('/api/fs/list', 'post', data, function (rsp,status) {
            files[path] = rsp.data
            alistHelper.compareFiles(files)
        });
    };
    alistHelper.makeRequest = function(url, method, data, callback) {
        $.ajax({
          url: url,
          data: JSON.stringify(data),
          contentType: "application/json",
          type: method,
          beforeSend: function(request) {
            request.setRequestHeader("Authorization",localStorage.getItem('token'));
          },
          success: callback
        });
    };
    alistHelper.mkdir = function(path) {
        let data = {path: path}
        return alistHelper.makeRequest('/api/fs/mkdir', 'post', data, function (rsp,status) {
        })
    };
    alistHelper.copyTask = function(src, dst, fileList) {
        if (!fileList || fileList.length <=0) return
         let data = {
            "src_dir": src,
            "dst_dir": dst,
            "names": []
        }
        const count = 50;
        let index = 0;
        while (index < fileList.length) {
            const lst = fileList.slice(index, index + count);
            index = index + count;
            for (let obj of lst) {
                data.names.push(obj.name)
            }
            alistHelper.makeRequest('/api/fs/copy', 'post', data, function (rsp,status) {
            })
        }
    };
    // 移动云盘保存分享
    alistHelper.saveShare = function() {
        let ele = $('.row-select')
        if (ele.length === 0) {
            return
        }
        if ($('.btn-listselect').text().indexOf('0项') > 0) {
            ele.click()
        }
        ele=$('.btn-listaction_save')
        if (ele.length === 0) {
            return
        }
        if (!alistHelper.saveButtonClick) {
            ele[0].click()
            alistHelper.saveButtonClick = 1
            return
        }
        if (!alistHelper.folderSelect || alistHelper.folderSelect < 10) {
            let folder=(new Date()).format('yyyy-MM-dd')
            if (!alistHelper.folderSelect || alistHelper.folderSelect === 4) {
                alistHelper.folderSelect = alistHelper.folderSelect === undefined ? 0 : alistHelper.folderSelect
                ele = $('.el-tree-node.is-expanded.is-focusable')
                if (ele.length === 0) return
                for (let i=1;i<ele.length; ++i) {
                    let e = $(ele[i])
                    if (!e.text()) continue
                    if (e.text().indexOf(folder) >= 0) {
                        e.click()
                        alistHelper.folderSelect = 11
                        return
                    }
                }
            }
            if  (alistHelper.folderSelect < 1) {
                $('.el-icon-plus').click()
                alistHelper.folderSelect = 1
                console.log(alistHelper.folderSelect, new Date())
                return
            }
            if  (alistHelper.folderSelect < 2) {
                let e = $('.el-input__inner')
                if (e.length === 0||e.length>1) return
                console.log(e)
                let v1 = e.attr('value')
                e.attr('value', folder)
                e[0].value = folder
                alistHelper.folderSelect = alistHelper.folderSelect<1.5 ? 1.5 : 2
                console.log(alistHelper.folderSelect, new Date(), e.attr('value'), v1)
                return
            }
            if  (alistHelper.folderSelect < 3) {
                let e = $('.el-input__inner')
                if (e.length === 0||e.length>1) return
                const evt = new Event('input');
                if (alistHelper.folderSelect > 2) e.attr('value', folder)
                alistHelper.folderSelect = alistHelper.folderSelect<2.5 ? 2.5 : 3
                console.log(alistHelper.folderSelect, new Date(), e.attr('value'), e[0].dispatchEvent(evt))
                return
            }
            if  (alistHelper.folderSelect < 4) {
                $('.el-button.el-button--text.el-button--mini')[0].click()
                alistHelper.folderSelect = 4
                console.log(alistHelper.folderSelect, new Date())
                return
            }
        }
        if (!alistHelper.saving) {
            ele = $('.el-button.el-button--primary')
            for (let i=0;i<ele.length; ++i) {
                let e = ele[i]
                if ($(e).text().indexOf('转存') >= 0) {
                    e.click()
                    alistHelper.saving = 1
                }
            }
        }
        if (alistHelper.saved !== 5) {
            alistHelper.saved = alistHelper.saved || 1
            alistHelper.saved += 1
            if (alistHelper.saved === 5) {
                clearInterval(alistHelper.timer)
                alistHelper.timer = 0
                window.close()
            }
        }
    }
    
    // 移动云盘分享链接查找
    alistHelper.linkSearch = function() {
        if (alistHelper.w && alistHelper.w.closed === false) {
            if (!alistHelper.count) {
                alistHelper.count = 1
            } else {
                alistHelper.count += 1
            }
            if (alistHelper.count > 30) {
                alistHelper.w.close()
                console.log('close')
                alistHelper.count = 0
            }
            return
        }
        if (!alistHelper.txt) {
            let t = window.getSelection().toString()
            if (/https\:\/\/caiyun.139.com\/m\/i\?\w+/.exec(t)) {
                alistHelper.txt = $('.left').text() //topicContent
            }
        }
        if (alistHelper.txt) {
            let rg = /https\:\/\/caiyun.139.com\/m\/i\?\w+/.exec(alistHelper.txt)
            if (!rg) {
                return
            }
            let t = rg[0]
            alistHelper.txt = alistHelper.txt.substring(rg.index + t.length)
            alistHelper.w = window.open(t, '', 'width=800,height=600')
            console.log(new Date(), t)
            alistHelper.count = 0
        }
        
    }
    function addButton() {
        if (window.location.href.indexOf('yun.139.com') > 0) {
            if (window.location.pathname.indexOf('/w/i/') >= 0) {
                alistHelper.saveShare()
            }
        } else if (window.location.href.indexOf('www.91panta.cn') > 0) {
            if (window.location.pathname.indexOf('/thread') >= 0) {
                alistHelper.linkSearch()
            }
        } else {
            if (window.location.pathname.indexOf('@manage') > 0) {
                if (window.location.pathname.indexOf('tasks/copy') > 0) {
                    alistHelper.addAutoRetry();
                }
            } else {
                alistHelper.addCompareBtn();
            }
        }
    };
    alistHelper.timer = setInterval(addButton, 3000);
})();